package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.View.MeasureSpec
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.components.LimitLine
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.utils.MPPointF
import com.lancoo.znbkxx.teacher.Ext.Companion.RZZD_URL
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.TraitInfo
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import kotlinx.android.synthetic.main.fragment_exercises_trait.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import kotlinx.android.synthetic.main.view_hint_num.view.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException


/**
 * @author : Admin
 * @date   : 2020/12/9
 * @desc   :
 */
class ExerciseTraitFragment : BaseFragment() {
    private val barEntries = mutableListOf<BarEntry>()
    private val xLabels = mutableListOf<String>()
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_exercises_trait
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        getStuExerciseTrait()
    }

    @SuppressLint("CheckResult")
    fun getStuExerciseTrait() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["StuID"] = viewModel.StuID.value
        method.getStuExerciseTrait(RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                val avgPercent = BigDecimal(it.Data.QuesAvgErrorRate * 100).setScale(0,
                        RoundingMode.HALF_UP)
                val careless = BigDecimal(it.Data.QuesCarelessRate * 100).setScale(0,
                        BigDecimal.ROUND_HALF_UP)
                initHint(it.Data, avgPercent, careless)
                initBarChart(it.Data, avgPercent)
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("SetTextI18n")
    private fun initHint(data: TraitInfo, avgPercent: BigDecimal, careless: BigDecimal) {
        when (data.Conclusion) {
            1 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_exercise_c)
                tv_child.text = "知识点掌握不牢"
                tv_child.setTextColor(Color.parseColor("#ffd234"))
                tv_sub.text = HtmlUtils.setText(
                        "错题较多噢，试题平均错误率较高，已达到<font color='#ffd234'>${avgPercent}%</font>")
            }
            2 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_exercise_b)
                tv_child.text = "做题马虎"
                tv_child.setTextColor(Color.parseColor("#22d7bb"))
                tv_sub.text = HtmlUtils.setText(
                        "<font color='#22d7bb'>${careless}%</font>错题由于粗心大意导致的；错题较多噢，试题平均错误率较高，已达到<font color='#22d7bb'>${avgPercent}%</font>")
            }
            else -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_exercise_a)
                tv_child.text = "做题又快又好"
                tv_child.setTextColor(Color.parseColor("#2dbcff"))
                tv_sub.visibility = View.GONE
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initBarChart(data: TraitInfo, avgPercent: BigDecimal) {
        barEntries.clear()
        xLabels.clear()
        data.TypeInfoList.forEachIndexed { index, typeInfo ->
            val barEntry = BarEntry(index.toFloat() + 0.5f,
                    floatArrayOf((typeInfo.TypeWrongRate * 100f).toFloat(),
                            (typeInfo.TypeCarelessRate * 100.toFloat()).toFloat()))
            if (index == 0) {
                val view = layoutInflater.inflate(R.layout.view_hint_num, null)
                view.tv_percent.text = "${(typeInfo.TypeWrongRate * 100).toInt()}%"
                val drawable = BitmapDrawable(resources, convertViewToBitmap(view))
                barEntry.icon = drawable
            }
            barEntries.add(barEntry)
            xLabels.add(typeInfo.SectionName)
        }
        bc_exercise.apply {
            axisLeft.apply {
                isEnabled = true
                setDrawGridLines(true)
                setDrawAxisLine(true)
                setDrawLabels(true)
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = 110f
                addLimitLine(
                        LimitLine((data.QuesAvgErrorRate * 100).toFloat(), "${avgPercent}%").apply {
                            textColor = Color.parseColor("#ed5b5b")
                        })
                textColor = Color.parseColor("#999999")
            }
            axisRight.isEnabled = false
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            setScaleEnabled(false)
            //设置x轴显示在下方
            xAxis.apply {
                axisMinimum = 0f
                axisMaximum = data.TypeInfoList.size.toFloat()
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                labelCount = xLabels.size
                setCenterAxisLabels(true)
                //设置X轴文本旋转角度
                setDrawAxisLine(false)
                setDrawGridLines(false)
                //设置X轴文本大小
                textSize = 11f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
            }
            setVisibleXRangeMaximum(5f)
            val barDataSet = BarDataSet(barEntries, "")
            barDataSet.colors = listOf(Color.parseColor("#2dbcff"), Color.parseColor("#22d7bb"))
            barDataSet.iconsOffset = MPPointF(0f, 5f)
            val barData = BarData(barDataSet)
            barData.setDrawValues(false) //是否显示柱子的数值
            val widthScale = if (data.TypeInfoList.size >= 5) 1f else data.TypeInfoList.size.toFloat() / 5
            barData.barWidth = 0.27f * widthScale  //每个柱子的宽度
            this.data = barData
            val markerView = MyMarkView(requireContext(), R.layout.item_achievement_markview)
            markerView.chartView = this
            marker = markerView
            animateXY(1000, 1000)
        }
    }

    private fun convertViewToBitmap(view: View): Bitmap {
        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, DensityUtils.dp2px(requireContext(), 32f),
                DensityUtils.dp2px(requireContext(), 32f))
        view.buildDrawingCache()
        return view.drawingCache
    }

    inner class MyMarkView(context: Context, layoutResource: Int) :
            MarkerView(context, layoutResource) {
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val label = chartView.xAxis.valueFormatter.getFormattedValue(e!!.x - 0.5f,
                    chartView.xAxis)
            val barEntry = e as BarEntry
            tv_hint.text = "${label}\n非粗心大意：${barEntry.yVals[0].toInt()}%\n粗心大意：${barEntry.yVals[1].toInt()}%"
            super.refreshContent(e, highlight)
        }
    }
}